package com.test.controller;


import com.test.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @description: Controller基础类
 */
public class BaseController {

    /** 排序参数名称（create_time,desc;rank,asc）*/
    private static final String ORDER_PARAM = "orders";
    /** 当前页号参数名称（从1开始计数）*/
    private static final String PAGENUMBER_PARAM = "pageNumber";
    /** 每页记录数参数名称 */
    private static final String PAGESIZE_PARAM = "pageSize";
    /** 默认每页记录数 */
     private static final int DEFAULT_PAGESIZE = 20;


    @Autowired
    protected ExceptionHandler exceptionHandler;

    private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";

    protected Result genSuccessResult() {
        return new Result()
                .setStatus(ResultCode.SUCCESS)
                .setMsg(DEFAULT_SUCCESS_MESSAGE);
    }

    protected Result genSuccessResult(Object data) {
        return new Result()
                .setStatus(ResultCode.SUCCESS)
                .setMsg(DEFAULT_SUCCESS_MESSAGE)
                .setData(data);
    }

    protected Result genFailResult(String message) {
        return new Result()
                .setStatus(ResultCode.FAIL)
                .setMsg(message);
    }

    protected PageRequest buildPageRequest(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        boolean pageQuery = false;
        int pagesize = DEFAULT_PAGESIZE;
        int pageNumber = 1;
        String orderStrs = null;

        if (StringUtils.isNumeric(request.getParameter(PAGESIZE_PARAM))) {
            pagesize = Integer.parseInt(request.getParameter(PAGESIZE_PARAM), 10);
            pageQuery = true;
        }
        if (StringUtils.isNumeric(request.getParameter(PAGENUMBER_PARAM))) {
            pageNumber = Integer.parseInt(request.getParameter(PAGENUMBER_PARAM), 10);
            pageQuery = true;
        }
        if (StringUtils.isNotEmpty(request.getParameter(ORDER_PARAM))) {
            orderStrs = request.getParameter(ORDER_PARAM);
            pageQuery = true;
        }

        if (!pageQuery) {
            return null;
        }

        return SearchHelper.buildPageRequest(pageNumber, pagesize, orderStrs);
    }

    /**
     * 查询实体，可在子类里调用
     * @param formData 包装了查询条件的对象
     */




}
